package com.emergency.db.service.impl.staff;

import com.emergency.common.util.CommonUtils;
import com.emergency.common.util.IdWorker;
import com.emergency.db.dao.staff.StaffDao;
import com.emergency.db.dao.staff.StaffDetailDao;
import com.emergency.db.dao.staff.StaffStatusDao;
import com.emergency.db.domain.staff.Staff;
import com.emergency.db.domain.staff.StaffDetail;
import com.emergency.db.domain.staff.StaffStatus;
import com.emergency.db.service.staff.StaffService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class StaffServiceImpl implements StaffService {
    private final static Logger logger = LoggerFactory.getLogger(StaffServiceImpl.class);

    @Autowired
    private StaffDao staffDao;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private StaffDetailDao staffDetailDao;


    //保存
    public Long save(Staff staff) {
        if (CommonUtils.isNullOrEmpty(staff.getId())) {
            staff.setId(idWorker.nextId());
            staff.setCreateTime(new Date());
        }
        //保存员工基本信息
        staffDao.save(staff);
        //保存员工细则信息
        staffSave(staff);
        return staff.getId();
    }

    private void staffSave(Staff staff) {
        StaffDetail staffDetail = staff.getStaffDetail();
        if (CommonUtils.isNullOrEmpty(staffDetail.getId())) {
            staffDetail.setId(idWorker.nextId());
            staffDetail.setStaff(staff);
        }
        staffDetailDao.save(staffDetail);
    }


    //批量保存
    public void saveAll(List<Staff> staffList) {
        staffList.forEach(staff -> {
            if (CommonUtils.isNullOrEmpty(staff.getId())) {
                staff.setId(idWorker.nextId());
                staff.setCreateTime(new Date());
            }
            staffDao.save(staff);
            //保存员工细则信息
            staffSave(staff);
        });
    }

    //查询单项
    public Staff findById(Long id) {
        Staff staff = staffDao.findById(id).orElse(null);
        if (CommonUtils.isNullOrEmpty(staff)) {
            logger.info("此员工信息为空！");
            return staff;
        }
        staff.setStaffDetail(staffDetailDao.findByStaff(id));
        return staff;
    }

    //删除
    public void delete(Long id) {
        staffDetailDao.deleteByStaff(id);
        staffDao.deleteById(id);
    }

    //查询全部
    @Override
    public List<Staff> findAll() {
        List<Staff> staffList = staffDao.findAll();
        staffList.forEach(staff -> {
            staff.setStaffDetail(staffDetailDao.findByStaff(staff.getId()));
        });
        return staffList;
    }

    //分页查询
    @Override
    public Page<Staff> findList(Map searchMap, int page, int size) {
        Specification<Staff> specification = createSpecification(searchMap);
        Sort sort = Sort.by(Sort.Direction.ASC, "id");
        PageRequest pageRequest = PageRequest.of(page - 1, size, sort);
        Page<Staff> staffList = staffDao.findAll(specification, pageRequest);
        staffList.forEach(staff -> {
            staff.setStaffDetail(staffDetailDao.findByStaff(staff.getId()));
        });
        return staffList;
    }

    /**
     * 动态条件构建
     *
     * @param searchMap
     * @return
     */
    private Specification<Staff> createSpecification(Map searchMap) {
        return new Specification<Staff>() {

            @Override
            public Predicate toPredicate(Root<Staff> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<Predicate>();

                // 姓名
                if (searchMap.get("name") != null && !"".equals(searchMap.get("name"))) {
                    predicateList.add(criteriaBuilder.like(root.get("name").as(String.class), "%" + (String) searchMap.get("name") + "%"));
                }
                //隶属分队
                if (searchMap.get("army") != null && !"".equals(searchMap.get("army"))) {
                    predicateList.add(criteriaBuilder.equal(root.get("army").as(String.class), (String) searchMap.get("army")));
                }
                //小组
                if (searchMap.get("sGroup") != null && !"".equals(searchMap.get("sGroup"))) {
                    predicateList.add(criteriaBuilder.equal(root.get("sGroup").as(String.class), (String) searchMap.get("sGroup")));
                }
                //小队
                if (searchMap.get("team") != null && !"".equals(searchMap.get("team"))) {
                    predicateList.add(criteriaBuilder.equal(root.get("team").as(String.class), (String) searchMap.get("team")));
                }
                //小队集合
                if (searchMap.get("teamSet") != null && !"".equals(searchMap.get("teamSet"))) {
                    predicateList.add(criteriaBuilder.equal(root.get("teamSet").as(String.class), (String) searchMap.get("teamSet")));
                }
                // 主要任务
                if (searchMap.get("task") != null && !"".equals(searchMap.get("task"))) {
                    predicateList.add(criteriaBuilder.like(root.get("task").as(String.class), "%" + (String) searchMap.get("task") + "%"));
                }
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
    }
}
